package edu.ucsb.cs176b.android;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;

public class DBUtil{
	
    private static final String DATABASE_NAME = "th";
    private static final String TABLE_NAME = "th";
    private static final int DATABASE_VERSION = 1;

    private static final String CREATE_TABLE =
        "create table users (username text primary key not null, "
        + "token text not null, host text not null);";
    
    private final Context context;
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public DBUtil(Context ctx) 
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }
    
	public void addUser(String username, String token, String host) {
		db=DBHelper.getWritableDatabase();
		ContentValues cv=new ContentValues();
		cv.put("username", username);
		cv.put("token", token);
		cv.put("host", host);
		db.insert("users", "huh", cv);
		db.close();
	}
	
	public ArrayList<String> getUsers() {
		db=DBHelper.getReadableDatabase();
		String[] columns = new String[]{"username", "token", "host"};
		Cursor c = db.query("users", columns, null, null, null, null, null);
		ArrayList<String> users = new ArrayList<String>();
		
		while(c.moveToNext()){
			String username = c.getString(c.getColumnIndex("username"));
			String token = c.getString(c.getColumnIndex("token"));
			String host = c.getString(c.getColumnIndex("host"));
			String resString = username+","+token+","+host;
			users.add(resString);
		}
		c.close();
		db.close();
		return users;
	}
    

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

    	public void onCreate(SQLiteDatabase db) {
    		db.execSQL(CREATE_TABLE);
    	}

    	
    	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {	
    		db.execSQL("DROP TABLE IF EXISTS users");
    		onCreate(db);
    	}
    	

    }  

	




 
}
